﻿namespace TomatoBreak.Infrastructure
{
    using System;
    using System.Web.Mvc;

    public class ModelBinderProvider : IModelBinderProvider
    {
        private readonly IDependencyResolver resolver;
        private readonly TypeMappingRegistry<object, IModelBinder> registry;

        public ModelBinderProvider(IDependencyResolver resolver, TypeMappingRegistry<object, IModelBinder> registry)
        {
            if (resolver == null)
            {
                throw new ArgumentNullException("resolver");
            }

            if (registry == null)
            {
                throw new ArgumentNullException("registry");
            }

            this.resolver = resolver;
            this.registry = registry;
        }

        public virtual IModelBinder GetBinder(Type modelType)
        {
            return registry.IsRegistered(modelType) ?
                   resolver.GetService(registry.Matching(modelType)) as IModelBinder :
                   null;
        }
    }
}